<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%" align-center :close-on-click-modal="false"
    :close-on-press-escape="false" @close="handleClose">
    <div class="billing-config-dialog">
      <!-- 当前账期展示 -->
      <div class="enterprise-info">
        <h3>{{ settleBillTotalDetail.shortName }} - 结算单明细</h3>
      </div>
      <div class="detail-section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="当前账期" span="2">
            {{ settleBillTotalDetail.billPeriod || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="开始日期">
            {{ settleBillTotalDetail.startDate }}
          </el-descriptions-item>
          <el-descriptions-item label="结束日期">
            {{ settleBillTotalDetail.endDate }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- 计费配置内容 -->
      <div class="config-content">
        <el-form ref="formRef" :model="formItem" :rules="rules" label-width="120px">
          <el-form-item label="明细名称" prop="detailName">
            <el-input v-model="formItem.detailName" placeholder="请输入明细名称" clearable style="width: 60%" />
          </el-form-item>
          <!-- <el-form-item label="对象类型" prop="objectType">
            <el-select v-model="formItem.objectType" placeholder="请选择对象类型" clearable style="width: 60%"
              @change="handleObjectTypeChange">
              <el-option label="全部" value="" />
              <el-option label="电表" value="电表" />
              <el-option label="水表" value="水表" />
              <el-option label="房租" value="房租" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="当期用量" prop="currentUsage">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-input-number v-model="formItem.currentUsage" :precision="2" :step="0.01" :min="0" style="width: 200px"
                controls-position="right" />
              <span>{{ usageUnit }}</span>
            </div>
          </el-form-item>

          <el-form-item label="计费单价" prop="unitPrice">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-input-number v-model="formItem.unitPrice" :precision="2" :step="0.01" :min="0" style="width: 200px"
                controls-position="right" />
              <span>元</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { addManualSettleBillDetail, updateManualSettleBillDetail } from '@/api/settle'
import { getUsageUnit } from '@/utils/index';

const emit = defineEmits(['reload'])

const dialogVisible = ref(false)
 // create, edit
const dialogStatus = ref('create')
const formRef = ref()
const usageUnit = ref('')
// 结算单汇总
const settleBillTotalDetail = ref({
  id: null,
  billPeriod: '',
  startDate: '',
  endDate: '',
  enterpriseId: null,
  shortName: '',
})
// 结算单明细
const settleBillDetail = ref({
  id: null,
  detailName: '',
  objectType: '',
  currentUsage: null,
  unitPrice: null,
})
const formItem = reactive({
  detailName: '',
  objectType: '',
  currentUsage: null,
  unitPrice: null,
})

const handleObjectTypeChange = (objectType: string) => {
  usageUnit.value = getUsageUnit(objectType)
}

// 打开弹窗
const openDialog = (
  editFlag: 'create' | 'edit',
  totalDetail: any,
  billDetail?: any
  ) => {
    dialogStatus.value = editFlag
    settleBillTotalDetail.value = totalDetail
    settleBillDetail.value = billDetail
    
  if (billDetail) {
    formItem.detailName = billDetail.detailName
    formItem.objectType = billDetail.objectType
    formItem.currentUsage = billDetail.currentUsage
    formItem.unitPrice = billDetail.unitPrice
    // 设置用量单位
    usageUnit.value = getUsageUnit(billDetail.objectType)
  }
  
  // 显示弹窗
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  // 重置数据
  settleBillTotalDetail.value = {
    id: null,
    billPeriod: '',
    startDate: '',
    endDate: '',
    enterpriseId: null,
    shortName: '',
  }
  settleBillDetail.value = {
    id: null,
    detailName: '',
    objectType: '',
    currentUsage: null,
    unitPrice: null,
  }
  usageUnit.value = ''
  reset()
}

const rules = computed(() => ({
  detailName: [
    { required: true, message: '请输入明细名称', trigger: 'blur' }
  ],
  // 对象类型验证已移除，通过传入参数确定
  currentUsage: [
    { required: true, message: '请输入当期用量', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入计费单价', trigger: 'blur' }
  ],
}))

const dialogTitle = computed(() => {
  switch (dialogStatus.value) {
    case 'create':
      return '新增结算单明细'
    case 'edit':
      return '编辑结算单明细'
    default:
      return '结算单明细信息'
  }
})

const reset = () => {
  Object.assign(formItem, {
    detailName: '',
    objectType: '',
    unitPrice: null,
    currentUsage: null
  })
  usageUnit.value = ''
  formRef.value?.clearValidate()
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let detailValue = settleBillTotalDetail.value
      if (dialogStatus.value === 'create') {
        // 构建新增结算单明细请求数据
        const addRequestData = {
          detailName: formItem.detailName,
          objectType: formItem.objectType,
          currentUsage: formItem.currentUsage,
          unitPrice: formItem.unitPrice,
          billPeriod: detailValue.billPeriod,
          startDate: detailValue.startDate,
          endDate: detailValue.endDate,
          settleBillTotalId: detailValue.id,
          enterpriseId: detailValue.enterpriseId,
        }

        try {
          addManualSettleBillDetail(addRequestData)
            .then((res: any) => {
              ElMessage.success("添加成功！");
              emit('reload');
            })
            .catch((err: any) => {
              console.error("err", err.msg);
              ElMessage.error("添加失败！");
            });
          dialogVisible.value = false
        } catch (error: any) {
          ElMessage.error(`新增结算单明细失败: ${error.message || '未知错误'}`)
        }
      } else if (dialogStatus.value === 'edit') {
        // 构建更新结算单明细请求数据
        const updateRequest = {
          id: settleBillDetail.value.id,
          detailName: formItem.detailName,
          objectType: formItem.objectType,
          currentUsage: formItem.currentUsage,
          unitPrice: formItem.unitPrice,
        }
        try {
          updateManualSettleBillDetail(updateRequest)
            .then((res: any) => {
              ElMessage.success("更新成功！");
              emit('reload');
            })
            .catch((err: any) => {
              console.error("err", err.msg);
              ElMessage.error("更新失败！");
            });
          dialogVisible.value = false
        } catch (error: any) {
          ElMessage.error(`更新结算单明细失败: ${error.message || '未知错误'}`)
        }
      }
    }
  })
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
.billing-config-dialog {
  display: flex;
  flex-direction: column;
}

.enterprise-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  
  h3 {
    margin: 0 0 8px 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
}

.detail-section {
  h3 {
    margin: 0 0 15px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #409EFF;
    padding-bottom: 8px;
  }
}

.config-content {
  margin-top: 20px;
  flex: 1;
  height: 50%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-descriptions) {
  .is-bordered {
    .el-descriptions__label.is-bordered-label {
      width: 20%;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 滚动条样式
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
  
  &:hover {
    background-color: #c0c4cc;
  }
}

::-webkit-scrollbar-track {
  background-color: #f5f7fa;
  border-radius: 3px;
}
</style>
